<!-- 新增与编辑仓库 -->
<template>
  <el-dialog
    :title="dialog.title"
    :visible.sync="dialog.show"
    width="530px"
    height="400px"
    custom-class="mydialog"
    append-to-body
    @close="handleClose"
  >
    <div class="dialog-content">
      <el-form ref="form1" :model="form" :rules="rules" label-width="150px">
        <el-form-item prop="name" label="仓库名称：">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item label="仓库人员：">
          <el-autocomplete
            v-model="form.person"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="仓库地址：">
          <el-input v-model="form.address"/>
        </el-form-item>
        <el-form-item label="仓库面积：" prop="area">
          <el-input v-model="form.area"/>
        </el-form-item>
      </el-form>
      <div class="text-center mt-30">
        <el-button class="greenbt bt-wd" type="primary" @click="saveFun('form1')">保存</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
var checkArea = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const regu = /^[0-9]+(\.[0-9]{1,2})?$/
    const rsCheck = regu.test(value)
    if (!rsCheck) {
      return callback(new Error('格式不正确'))
    }
  }
  callback()
}
import {
  getUserByWarehouseName,
  saveWarehouse,
  updateWarehouse
} from '@/api/pas/warehouse'
export default {
  props: {
    // 父组件调用时传进来的参数
    modalStaticData: {
      type: Object,
      default: () => {}
    },
    modalData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      dialog: {
        title: '',
        show: true
      },
      form: {
        name: '',
        person: '',
        personObj: null,
        address: '',
        area: '',
        phone: ''
      },
      rules: {
        name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
        area: [{
          required: true,
          validator: checkArea,
          trigger: 'blur'
        }]
      },
      // start
      userList: [],
      state: ''
      // end
    }
  },
  mounted() {
    this.getUserInWhere('')
    console.warn(this.userList)
    if (this.modalData.type === 'edict') {
      this.getUserInWhere(this.modalData.data.warehouseLinkman)
      this.dialog.title = '仓库编辑'
      this.form.name = this.modalData.data.warehouseName
      this.form.person = this.modalData.data.warehouseLinkman
      this.form.address = this.modalData.data.warehouseAddress
      this.form.area = this.modalData.data.warehouseAcreage
    } else {
      this.dialog.title = '仓库添加'
    }
  },
  methods: {
    getUserInWhere(queryString) {
      getUserByWarehouseName(queryString).then(res => {
        this.userList = res.data.data
        for (var i = 0; i < this.userList.length; i++) {
          this.userList[i].value = this.userList[i].name
        }
      })
    },
    handleClose() {
      this.$emit('close')
    },
    /**
       * 新增/修改仓库
       */
    saveFun(formName) {
      const self = this
      self.$refs[formName].validate(valid => {
        if (valid) {
          const formData = new FormData()
          formData.append('warehouseName', this.form.name.trim())
          if (this.form.personObj !== null) {
            formData.append('warehouseLinkman', this.form.personObj.name.trim())
            formData.append('warehouseLinkmanId', this.form.personObj.id.trim())
            formData.append('warehousePhone', this.form.personObj.mobile.trim())
          }
          formData.append('warehouseAddress', this.form.address.trim())
          formData.append(
            'warehouseAcreage',
            this.form.area ? this.form.area : ''
          )
          if (this.modalData.type !== 'edict') {
            // add
            console.log('warehouseName' + formData.get('warehouseName'))
            saveWarehouse(formData)
              .then(res => {
                console.warn(res)
                if (res.data.status === 'faild') {
                  this.$message.error(res.data.messge)
                } else {
                  this.$message({
                    message: '添加成功',
                    type: 'success'
                  })
                }
              })
              .finally(() => {
                this.dialog.show = false
                this.modalStaticData.closeChildAndRefresh()
              })
          } else {
            // update
            formData.append('warehouseId', this.modalData.data.warehouseId)
            updateWarehouse(formData)
              .then(res => {
                if (res.data.status === 'faild') {
                  this.$message.error(res.data.messge)
                } else {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                }
              })
              .finally(() => {
                this.dialog.show = false
                this.modalStaticData.closeChildAndRefresh()
              })
          }
        } else {
          return false
        }
      })
    },
    /**
       * 选中交互
       */
    handleSelect(item) {
      console.warn(item)
      this.form.personObj = item
      console.warn(this.form.personObj)
    },
    /**
       * 下拉框
       */
    querySearchAsync(queryString, cb) {
      this.getUserInWhere(queryString)
      var userList = this.userList
      var results = queryString
        ? userList.filter(this.createStateFilter(queryString))
        : userList
      cb(results)
    },
    createStateFilter(queryString) {
      return state => {
        return (
          state.value ? state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0 : false
        )
      }
    }
  }
}
</script>
